import React from 'react'
import { connect } from 'dva'
import { Page } from 'components'
import {
  Button,
  Card,
  Col,
  Row,
  Tabs,
  message,
  Modal,
  Input,
  Icon
} from 'antd'
import List from './List'
import ResourceList from './ResourceList'
import UserList from './UserList'
import SearchResourcesModal from './SearchResourcesModal'
import SearchUserModal from './SearchUserModal'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import styles from './List.less'
import UpdateRole from './UpdateRole'
import LwjTree from 'components/LwjTree'
import LwjTrees from 'components/LwjTrees'
import { showButton } from 'utils/promissionFilter'

const TabPane = Tabs.TabPane
const confirm = Modal.confirm
const Roles = ({ location, dispatch, role, app, loading }) => {
  const {
    items,
    pagination,
    isShowUpdateModal,
    isUpdate,
    currentUpdateItem,
    rowClicked,
    roleResources,
    isShowSearchResourceModal,
    resourcesItems,
    resourcePagination,
    toBeBoundResources,
    toBeUnBoundResources,
    isShowSearchUserModal,
    toBeBoundUser,
    toBeUnBoundUser,
    userItems,
    userPagination,
    roleUser,
    defaultActiveKey,
    menus,
    selectedMenus,
    bindMenuButtonVisible,
    resourceGrounpLists,
    boundResourceList
  } = role

  let { user, resources } = app

  const breadcrumbList = [
    {
      title: '系统管理'
    }, {
      title: '角色管理'
    }
  ]

  const treeProps = {
    dataSource: menus,
    multiple: true,
    checkable: true,
    defaultExpandAll: true,
    onCheck(value) {
      const childIds = value.map(function (childId) {
        return childId.id
      })
      const parentIds = value.map(function (childId) {
        return childId.parentId
      })
      const allIds = Array
        .from(new Set([
          ...childIds,
          ...parentIds
        ]))
        .filter(s => s !== null)

      dispatch({
        type: 'role/getSelectedMenus',
        payload: {
          selectedMenus: allIds
          // selectedMenus: childIds
        }
      })
      dispatch({
        type: 'role/showBindMenuButton',
        payload: {
          visible: false
        }
      })
    }
  }
  let roleItems = items.filter(item => {
    if (app.user && app.user.roles && app.user.roles.findIndex((e) => e.name === 'ROLE_ADMIN') > -1) {
      return true
    }
    switch (item.name) {
      case 'ROLE_USER':
        return false
      case 'ROLE_ADMIN':
        return false
      case 'ROLE_ANONYMOUS':
        return false
      default:
        return true
    }
  })

  /**
   *  获取要loading的接口
   */
  const getLoading = loading => loading.effects['role/query'] ||
    loading.effects['role/userGroupList'] ||
    loading.effects['role/listUserByRole'] ||
    loading.effects['role/getRoleMenu'] ||
    loading.effects['role/listResourceByRole']

  const listProps = {
    dataSource: roleItems,
    loading: getLoading(loading),
    pagination: false,
    pageChangeAction: 'role/query',
    dispatch,
    location,
    selectType: 'single',
    selectedRowKeys: [rowClicked],
    showRoleButton: showButton('role.showRoleButton', resources, user),
    onUpdateRole(record) {
      dispatch({
        type: 'role/toUpdateRole',
        payload: {
          currentRole: record
        }
      })
      dispatch({ type: 'role/showUpdateRoleModal', payload: {} })
    },
    onDeleteRole(record) {
      confirm({
        title: '您确认要删除该角色?',
        content: '该角色删除后，将会影响对应用户的操作权限',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: 'role/deleteRole',
            payload: {
              roleId: record.id,
              roleVersion: record.version
            }
          })
          dispatch({ type: 'role/emptyResources', payload: {} })
        },
        onCancel() { }
      })
    },
    onSelectRows(selectedRowKeys, selectRows) {
      dispatch({
        type: 'role/updateRowClicked',
        payload: {
          rowClicked: selectedRowKeys[0]
        }
      })

      // 获取当前角色拥有的权限 dispatch({   type: 'role/listResourceByRole',   payload: {
      // roleId: selectedRowKeys[0] } });
      if (defaultActiveKey === '1') {
        //选择之前先清空
        dispatch({ type: 'role/emptyresourceList', payload: {} })
        // 获取当前角色拥有资源组
        dispatch({
          type: 'role/userGroupList',
          payload: {
            roleId: selectedRowKeys[0]
          }
        })
      }
      if (defaultActiveKey === '2') {
        // 获取当前角色拥有的用户
        dispatch({
          type: 'role/listUserByRole',
          payload: {
            roleId: selectedRowKeys[0]
          }
        })
      }
      if (defaultActiveKey === '3') {
        //切换角色就把可选状态设置为false
        dispatch({
          type: 'role/showBindMenuButton',
          payload: {
            visible: true
          }
        })
        //选择之前先清空
        dispatch({ type: 'role/emptyMenu', payload: {} })
        //获取当前角色拥有的菜单
        dispatch({
          type: 'role/getRoleMenu',
          payload: {
            roleId: selectedRowKeys[0]
          }
        })
      }
      if (defaultActiveKey === '4') {
        // 获取当前角色拥有的权限
        dispatch({
          type: 'role/listResourceByRole',
          payload: {
            roleId: selectedRowKeys[0]
          }
        })
      }

    },
    onRowClick(record) {
      // 更新选中的行ID => rowClicked
      dispatch({
        type: 'role/updateRowClicked',
        payload: {
          rowClicked: record.id
        }
      })

      if (defaultActiveKey === '1') {
        //选择之前先清空
        dispatch({ type: 'role/emptyresourceList', payload: {} })
        // 获取当前角色拥有资源组
        dispatch({
          type: 'role/userGroupList',
          payload: {
            roleId: record.id
          }
        })
      }

      if (defaultActiveKey === '4') {
        // 获取当前角色拥有的权限
        dispatch({
          type: 'role/listResourceByRole',
          payload: {
            roleId: record.id
          }
        })
      }
      if (defaultActiveKey === '2') {
        // 获取当前角色拥有的用户
        dispatch({
          type: 'role/listUserByRole',
          payload: {
            roleId: record.id
          }
        })
      }
      if (defaultActiveKey === '3') {
        //切换角色就把可选状态设置为false
        dispatch({
          type: 'role/showBindMenuButton',
          payload: {
            visible: true
          }
        })
        //选择之前先清空
        dispatch({ type: 'role/emptyMenu', payload: {} })
        //获取当前角色拥有的菜单
        dispatch({
          type: 'role/getRoleMenu',
          payload: {
            roleId: record.id
          }
        })
      }
    }
  }

  const addRole = () => {
    dispatch({
      type: 'role/showUpdateRoleModal', payload: {
        isUpdate: false
      }
    })
  }

  const storeResources = () => {
    if (_.isEmpty(rowClicked)) {
      Modal.info({ title: '提示', content: `请先选择需要增加资源的角色` })
      return
    }
    // 获取要绑定的数据
    dispatch({
      type: 'role/storeResourcesGroup',
      payload: { boundResourceList, roleId: rowClicked }
    })
  }

  const refreshResources = () => {
    dispatch({
      type: 'role/refreshResourceGroup',
      payload: {}
    })
  }

  const updateModalProps = {
    visible: isShowUpdateModal,
    title: isUpdate
      ? '修改角色'
      : '添加角色',
    maskClosable: false,
    destroyOnClose: true,
    onOk(data) {
      const actionType = isUpdate
        ? 'role/updateRole'
        : 'role/createRole'
      dispatch({
        type: actionType,
        payload: {
          roleData: data
        }
      })
      message.success('操作成功')
    },
    onCancel(record) {
      dispatch({ type: 'role/hideUpdateRoleModal', payload: {} })
    },
    okText: '确认',
    cancelText: '取消',
    currentUpdateItem: currentUpdateItem
  }

  const searchResourcesModalProps = {
    visible: isShowSearchResourceModal,
    title: '选择资源',
    width: 1000,
    destroyOnClose: true,
    wrapClassName: 'vertical-center-modal',
    onOk() {
      // 角色资源绑定
      dispatch({
        type: 'role/bindResource',
        payload: {
          toBeBoundResources,
          rowClicked
        }
      })
    },
    onCancel() {
      dispatch({ type: 'role/hideSearchResourceModal', payload: {} })
    },
    okText: '确认',
    cancelText: '取消',
    dataSource: resourcesItems,
    pagination: resourcePagination,
    dispatch,
    toBeBoundResources
  }

  const resourceListProps = {
    dataSource: roleResources,
    selectedRowKeys: toBeUnBoundResources,
    onSelectResourceRows(selectedRowKeys, selectRows) {
      dispatch({
        type: 'role/updateToBeUnBoundResources',
        payload: {
          toBeUnBoundResources: selectedRowKeys
        }
      })
    }
  }

  const searchUserModalProps = {
    visible: isShowSearchUserModal,
    title: '选择用户',
    width: 1000,
    destroyOnClose: true,
    wrapClassName: 'vertical-center-modal',
    onOk() {
      // 角色用户绑定
      dispatch({
        type: 'role/bindUser',
        payload: {
          toBeBoundUser,
          rowClicked
        }
      })
    },
    onCancel() {
      dispatch({ type: 'role/hideSearchUserModal', payload: {} })
    },
    okText: '确认',
    cancelText: '取消',
    dataSource: userItems,
    boundUsers: roleUser,
    pagination: userPagination,
    dispatch,
    toBeBoundUser
  }

  const userListProps = {
    dataSource: roleUser,
    selectedRowKeys: toBeUnBoundUser,
    onSelectUserRows(selectedRowKeys, selectRows) {
      dispatch({
        type: 'role/updateToBeUnBoundUser',
        payload: {
          toBeUnBoundUser: selectedRowKeys
        }
      })
    }
  }

  /**
   * 绑定资源
   */
  const toBindResource = () => {
    if (_.isEmpty(rowClicked)) {
      Modal.info({ title: '提示', content: `请先选择需要增加资源的角色` })
      return
    }
    dispatch({ type: 'role/queryResources', payload: {} })
    dispatch({ type: 'role/showSearchResourceModal', payload: {} })
  }

  /**
   * 解绑资源
   */
  const unbindResource = () => {
    if (_.isEmpty(rowClicked)) {
      Modal.info({ title: '提示', content: `请选择需要解绑资源的角色` })
      return
    }
    if (!toBeUnBoundResources || toBeUnBoundResources.length === 0) {
      Modal.info({ title: '提示', content: `请选择该角色需要解绑的资源` })
      return
    }
    dispatch({
      type: 'role/unbindResource',
      payload: {
        toBeUnBoundResources,
        rowClicked
      }
    })
  }

  /**
   * 绑定用户
   */
  const toBindUser = () => {
    if (_.isEmpty(rowClicked)) {
      Modal.info({ title: '提示', content: `请先选择需要绑定用户的角色` })
      return
    }
    dispatch({ type: 'role/queryUser', payload: {} })
    dispatch({ type: 'role/showSearchUserModal', payload: {} })
  }

  /**
   * 解绑用户
   */
  const unbindUser = () => {
    if (_.isEmpty(rowClicked)) {
      Modal.info({ title: '提示', content: `请选择要解绑的角色` })
      return
    }
    if (!toBeUnBoundUser || toBeUnBoundUser.length === 0) {
      Modal.info({ title: '提示', content: `请选择要解绑的用户` })
      return
    }
    dispatch({
      type: 'role/unbindUser',
      payload: {
        toBeUnBoundUser,
        rowClicked
      }
    })
  }

  const toBindMenu = () => {
    dispatch({
      type: 'role/bindMenu',
      payload: {
        roleId: rowClicked,
        menuIds: selectedMenus
      }
    })

  }

  /**
   * 切换tab的回掉
   * @param {*} activeKey
   */
  const onTagsChange = (activeKey) => {
    dispatch({ type: 'role/emptyRoleParams', payload: {} })
    dispatch({
      type: 'role/updateDefaultActiveKey',
      payload: {
        defaultActiveKey: activeKey
      }
    })
    // 清掉资源组
    dispatch({ type: 'role/emptyresourceList', payload: {} })
  }

  const frontSearch = (type) => {
    let value = ''
    if (type === 'resource') {
      value = document
        .getElementById('searchResourceInput')
        .value
    } else {
      value = document
        .getElementById('searchUserInput')
        .value
    }
    dispatch({
      type: 'role/frontSearch',
      payload: {
        searchText: value,
        roleId: rowClicked,
        searchType: type
      }
    })
  }

  // 资源组树结构
  const ResourceGrunpTreeProps = {
    dataSource: resourceGrounpLists,
    multiple: true,
    checkable: true,
    defaultExpandAll: true,
    onCheck(value) {
      dispatch({
        type: 'role/bindResourceList',
        payload: value
      })
    }
  }

  return (
    <PageHeaderLayout title="角色管理" breadcrumbList={breadcrumbList}>
      <Page inner>
        <Tabs defaultActiveKey={defaultActiveKey} onChange={onTagsChange} type="card">
          {/* 暂时不用 */}
          {showButton('role.bindRes', resources, user) && <TabPane tab="角色绑定资源" key="4">
            <Row>
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableList}>
                    <div className={styles.tableListOperator}>
                      {showButton('role.addRole', resources, user) && <Button
                        size="small"
                        icon="plus"
                        type="primary"
                        onClick={() => addRole()}>
                        添加角色
                      </Button>}
                    </div>
                    <List {...listProps} />
                  </div>
                </Card>
              </Col>
              <UpdateRole {...updateModalProps} />
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.searchBanner}>
                    <div className={styles.banner}>
                      <Button
                        size="small"
                        icon="plus"
                        type="primary"
                        onClick={() => toBindResource()}>
                        绑定资源
                      </Button>
                      <Button
                        size="small"
                        icon="delete"
                        type="primary"
                        onClick={() => unbindResource()}>
                        解绑资源
                      </Button>
                      <Input placeholder="请输入资源名称或URL" className={styles.input} id="searchResourceInput"
                        onPressEnter={() => frontSearch('resource')} />
                      <Button
                        size="small"
                        icon="search"
                        type="primary"
                        onClick={() => frontSearch('resource')}>
                      </Button>
                    </div>
                    <ResourceList {...resourceListProps} />
                    <SearchResourcesModal {...searchResourcesModalProps} />
                  </div>
                </Card>
              </Col>
            </Row>
          </TabPane>}

          {showButton('role.bindResGroup', resources, user) && <TabPane tab="角色绑定资源组" key="1">
            <Row>
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableList}>
                    <div className={styles.tableListOperator}>
                      {showButton('role.addRole', resources, user) &&
                        <Button size="small" icon="plus" type="primary" onClick={() => addRole()}>
                          添加角色
                      </Button>}
                    </div>
                    <List {...listProps} />
                  </div>
                </Card>
              </Col>
              <UpdateRole {...updateModalProps} />
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableListOperator}>
                    <Button size="small" icon="edit" type="primary" onClick={() => storeResources()}>
                      保存
                    </Button>
                    <Button size="small" icon="reload" type="primary" onClick={() => refreshResources()}
                      style={{ left: '10px' }}>
                      刷新
                    </Button>
                    <h3
                      style={{
                        color: '#33bdb8',
                        marginBottom: 10
                      }}><Icon type="github" style={{ marginRight: 10 }} />当前角色资源组</h3>
                    {resourceGrounpLists !== undefined && resourceGrounpLists.length !== 0 &&
                      <LwjTrees {...ResourceGrunpTreeProps} />}
                  </div>
                </Card>
              </Col>
            </Row>
          </TabPane>}

          <TabPane tab="角色绑定用户" key="2">
            <Row>
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableList}>
                    <div className={styles.tableListOperator}>
                      {showButton('role.addRole', resources, user) &&
                        <Button size="small" icon="plus" type="primary" onClick={() => addRole()}>
                          添加角色
                      </Button>}
                    </div>
                    <List {...listProps} />
                  </div>
                </Card>
              </Col>
              <UpdateRole {...updateModalProps} />
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.searchBanner}>
                    <div className={styles.banner}>
                      <Button size="small" icon="plus" type="primary" onClick={() => toBindUser()}>
                        绑定用户
                      </Button>
                      <Button size="small" icon="delete" type="primary" onClick={() => unbindUser()}>
                        解绑用户
                      </Button>
                      <Input placeholder="请输入用户数据" id="searchUserInput" className={styles.input}
                        onPressEnter={() => frontSearch('user')} />
                      <Button
                        size="small"
                        icon="search"
                        type="primary"
                        onClick={() => frontSearch('user')} />
                    </div>
                    <UserList {...userListProps} />
                    <SearchUserModal {...searchUserModalProps} />
                  </div>
                </Card>
              </Col>
            </Row>
          </TabPane>

          {showButton('role.bindMenu', resources, user) && <TabPane tab="角色绑定菜单" key="3">
            <Row>
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableList}>
                    <div className={styles.tableListOperator}>
                      {showButton('role.addRole', resources, user) &&
                        <Button size="small" icon="plus" type="primary" onClick={() => addRole()}>
                          添加角色
                      </Button>}
                    </div>
                    <List {...listProps} />
                  </div>
                </Card>
              </Col>
              <UpdateRole {...updateModalProps} />
              <Col span={12}>
                <Card bordered={false}>
                  <div className={styles.tableList}>
                    <div className={styles.tableListOperator}>
                      <Button
                        size="small"
                        icon="plus"
                        type="primary"
                        disabled={bindMenuButtonVisible}
                        onClick={() => toBindMenu()}>
                        更新绑定菜单
                      </Button>
                    </div>
                    {menus !== undefined && menus.length !== 0 && <LwjTree {...treeProps} />}
                  </div>
                </Card>
              </Col>
            </Row>
          </TabPane>}
        </Tabs>
      </Page>
    </PageHeaderLayout>
  )
}

export default connect(({ role, app, loading }) => ({ role, app, loading }))(Roles)
